package servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.persistence.EntityManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.Item;
import entity.User;

import service.ItemService;
import service.UserService;
import session.Cart;
import util.JpaUtil;
public class Login extends HttpServlet {

	@EJB Cart cart;
	
	UserService userService=new UserService();
	ItemService itemService=new ItemService();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		RequestDispatcher dispatcher = request.getRequestDispatcher("Login.jsp");
		if (dispatcher != null) dispatcher.forward(request, response);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username=request.getParameter("username");
		String password=request.getParameter("password");

		User user=  userService.login(username, password);
		
		if(user!=null){   
			
			List<Item> items=itemService.getItems();
			
			cart.setItems(items);
			response.sendRedirect("home");			
			
		}else{
			
			request.setAttribute("error", "Login failed!");
			
			RequestDispatcher dispatcher = request.getRequestDispatcher("Login.jsp");
			if (dispatcher != null) dispatcher.forward(request, response);
		}
	}
}
